/**
 * 聊天状态管理
 */
import { defineStore } from 'pinia';
import type { ChatMessage, Reference, ApiResponse } from '../types';
import { request } from '../utils/request';

export const useChatStore = defineStore('chat', {
  state: () => ({
    messages: [] as ChatMessage[],
    loading: false,
    error: '',
  }),
  
  getters: {
    // 获取消息历史
    getMessageHistory: (state) => {
      return state.messages.map(msg => ({
        content: msg.content,
        role: msg.role
      }));
    },
    
    // 当前是否在加载状态
    isLoading: (state) => state.loading,
    
    // 是否存在错误消息
    hasError: (state) => !!state.error,
  },
  
  actions: {
    /**
     * 初始化聊天状态
     */
    init() {
      this.messages = [];
      this.loading = false;
      this.error = '';
    },
    
    /**
     * 添加消息到历史记录
     * @param message 聊天消息
     */
    addMessage(message: ChatMessage) {
      this.messages.push(message);
    },
    
    /**
     * 清空所有消息
     */
    clearMessages() {
      this.messages = [];
      this.error = '';
    },
    
    /**
     * 设置加载状态
     * @param status 加载状态
     */
    setLoading(status: boolean) {
      this.loading = status;
    },
    
    /**
     * 设置错误信息
     * @param message 错误消息
     */
    setError(message: string) {
      this.error = message;
    },
    
    /**
     * 发送消息并处理响应
     * @param content 消息内容
     */
    async sendMessage(content: string) {
      try {
        // 添加用户消息
        const userMessage: ChatMessage = {
          id: Date.now().toString(),
          content,
          role: 'user',
          timestamp: Date.now()
        };
        
        this.messages.push(userMessage);
        this.loading = true;
        this.error = '';
        
        // 准备历史消息
        const history = this.getMessageHistory;
        
        // API请求
        const response = await request<ApiResponse<{
          content: string;
          references?: Reference[];
        }>>('/api/chat', {
          method: 'POST',
          data: {
            query: content,
            history
          }
        });
        
        // 添加AI回复
        const assistantMessage: ChatMessage = {
          id: Date.now().toString(),
          content: response.data.content,
          role: 'assistant',
          timestamp: Date.now(),
          references: response.data.references
        };
        
        this.messages.push(assistantMessage);
        
      } catch (error) {
        this.error = '发送消息失败，请稍后再试';
        console.error('Error sending message:', error);
      } finally {
        this.loading = false;
      }
    },
  },
},{
    persist: true,
}); 